<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // 自定义一个栈结构:后进先出
        function Stack(){

            this.arr = []
            // 入栈
            Stack.prototype.push = (item) => {
                return this.arr.push(item)
            }

            // 出栈
            Stack.prototype.pop = () =>{
                return this.arr.pop()
            }

            // 查看栈顶,并返回该元素，但不删除
            Stack.prototype.popTop = () =>{
                return this.arr[this.arr.length-1]
            }

            // 查看是否为空
            Stack.prototype.isEmpty = () =>{
                return this.arr.length === 0
            }
            // 
        }

        // let obj1 = new Stack()
        // obj1.push(1)
        // obj1.push(2)
        // obj1.push(3)
        // console.log(obj1)
        // console.log(obj1.pop())
        // console.log(obj1)
        // obj1.pop()
        // console.log(obj1)
        // console.log(obj1.isEmpty())

        // let obj2 = new Stack()
        // obj2.push(1)
        // console.log(obj2)

        // 栈实现十进制转为二进制
        function dec2bin( decNum ){
            // 定义一个保存余数的栈
            const stack = new Stack()

            // 1、只要decNum大于0，将不断求余2
            while( decNum > 0 ){
                // 2、将余数入栈
                stack.push( decNum % 2)
                // 3、将求得的商重新赋值给原来的数
                decNum = Math.floor(decNum / 2 )
            }
            let binStr = ''
            // 只要栈不为空
            while( !stack.isEmpty()){
                //  依次出栈，将其拼接，即为二进制值
                console.log(stack)
                binStr += stack.pop()
            }
            return binStr
        }  

        alert(dec2bin(1010))
        alert(dec2bin(100))
        alert(dec2bin(10))
        alert(dec2bin(2))

    </script>
</body>
</html>